package config

import (
	"errors"
	"io/ioutil"
	"os"

	"gopkg.in/yaml.v2"
)

type _config struct {
	DB      string `yaml:"db"`
	Gateway struct {
		Port int `yaml:"port"`
	} `yaml:"gateway"`

	Heartbeat struct {
		Interval int64  `yaml:"interval"`
		URL      string `yaml:"url"`
	} `yaml:"heartbeat"`
}

var Config _config

func init() {
	Filepath := "carbon.yaml"
	LocalFilepath := "local_carbon.yaml"
	if _, err := os.Stat(Filepath); errors.Is(err, os.ErrNotExist) {
		panic(err)
	}

	content, err := ioutil.ReadFile(Filepath)
	if err != nil {
		panic(err)
	}

	err = yaml.Unmarshal(content, &Config)
	if err != nil {
		panic(err)
	}

	if _, err := os.Stat(LocalFilepath); !errors.Is(err, os.ErrNotExist) {
		content, err := ioutil.ReadFile(LocalFilepath)
		if err != nil {
			panic(err)
		}

		err = yaml.Unmarshal(content, &Config)
		if err != nil {
			panic(err)
		}
	}

	err = GetModule("module.json")
	if err != nil {
		panic(err)
	}
}
